package com.hippo.core.tuya

import android.app.Application
import android.content.Context
import android.util.Log
import com.google.gson.Gson
import com.hippo.core.BuildConfig
import com.hippo.core.core.ext.toJson
import com.hippo.core.core.manager.AppStore
import com.hippo.core.model.BasicData
import com.hippo.core.utils.UiHandler
import com.thingclips.smart.android.ble.api.LeScanSetting
import com.thingclips.smart.android.ble.api.ScanDeviceBean
import com.thingclips.smart.android.ble.api.ScanType
import com.thingclips.smart.android.user.api.IRegisterCallback
import com.thingclips.smart.android.user.api.IResetPasswordCallback
import com.thingclips.smart.android.user.api.IUidLoginCallback
import com.thingclips.smart.android.user.bean.User
import com.thingclips.smart.home.sdk.ThingHomeSdk
import com.thingclips.smart.home.sdk.bean.ConfigProductInfoBean
import com.thingclips.smart.home.sdk.bean.HomeBean
import com.thingclips.smart.home.sdk.bean.MessageHasNew
import com.thingclips.smart.home.sdk.builder.ActivatorBuilder
import com.thingclips.smart.home.sdk.callback.IThingGetHomeListCallback
import com.thingclips.smart.home.sdk.callback.IThingHomeResultCallback
import com.thingclips.smart.sdk.api.IMultiModeActivatorListener
import com.thingclips.smart.sdk.api.IThingActivatorGetToken
import com.thingclips.smart.sdk.api.IThingDataCallback
import com.thingclips.smart.sdk.api.IThingSmartActivatorListener
import com.thingclips.smart.sdk.bean.DeviceBean
import com.thingclips.smart.sdk.bean.MultiModeActivatorBean
import com.thingclips.smart.sdk.enums.ActivatorModelEnum


object TuYaManager {

    const val TAG = "TuYaManager"


    fun init(application: Application, appkey: String, appSerect: String) {
        ThingHomeSdk.init(application, appkey, appSerect)
        ThingHomeSdk.setDebugMode(BuildConfig.DEBUG)
    }

    fun requestMessageNew(callback: (Boolean) -> Unit) {
        ThingHomeSdk.getMessageInstance()
            .requestMessageNew(object : IThingDataCallback<MessageHasNew> {
                override fun onSuccess(result: MessageHasNew) {
                    Log.i(TAG, "onSuccess: ${result.toJson()}")
                    callback(result.isFamily || result.isNotification)
                }

                override fun onError(errorCode: String, errorMessage: String) {
                }
            })

    }


    fun loginOrRegisterWithUid(
        countryCode: String,
        uid: String,
        passwd: String,
        onSuccessCallback: (User?) -> Unit,
        onErrorCallback: (String?, String?) -> Unit,
    ) {
        ThingHomeSdk.getUserInstance().loginOrRegisterWithUid(
            countryCode,
            uid,
            passwd,
            true,
            object : IUidLoginCallback {

                override fun onSuccess(user: User?, homeId: Long) {
                    Log.i(TAG, "onSuccess: ${user.toJson()} homeId = $homeId")
                    AppStore.save("homeId", homeId)
                    onSuccessCallback(user)
                }

                override fun onError(code: String?, error: String?) {
                    onErrorCallback(code, error)
                }
            }
        )
    }


    fun registerAccountWithEmail(
        countryCode: String,
        email: String,
        passwd: String,
        code: String,
        onSuccessCallback: (User?) -> Unit,
        onErrorCallback: (String?, String?) -> Unit,
    ) {
        ThingHomeSdk.getUserInstance()
            .registerAccountWithEmail(countryCode, email, passwd, code, object : IRegisterCallback {
                override fun onSuccess(user: User?) {
                    onSuccessCallback(user)
                }

                override fun onError(code: String?, error: String?) {
                    onErrorCallback(code, error)
                }
            })

    }


    fun resetEmailPassword(onSuccess: () -> Unit, onError: (String, String) -> Unit) {
        ThingHomeSdk.getUserInstance()
            .resetEmailPassword("86", "123456@123.com", "123123", "a12345", object :
                IResetPasswordCallback {
                override fun onSuccess() {
                    onSuccess()
                }

                override fun onError(code: String?, error: String?) {
                    onError(code, error)
                }

            });
    }




    fun getHomeId(onSuccessCallback: (Long) -> Unit,onErrorCallback: (String) -> Unit) {
        ThingHomeSdk.getHomeManagerInstance().queryHomeList(object : IThingGetHomeListCallback {
            override fun onSuccess(homeBeans: List<HomeBean>?) {
                if (homeBeans?.isNotEmpty() == true) {
                    val homeId = homeBeans.first().homeId
                    onSuccessCallback(homeId)
                }
            }

            override fun onError(errorCode: String, error: String) {
                Log.i(TAG, "onError: $errorCode $error")
                onErrorCallback("onError: $errorCode, error = $error")
            }
        })
    }


    fun queryHomeList(
        onSuccessCallback: (List<HomeBean>) -> Unit,
        onErrorCallback: (String, String) -> Unit,
    ) {
        ThingHomeSdk.getHomeManagerInstance().queryHomeList(object : IThingGetHomeListCallback {
            override fun onSuccess(homeBeans: List<HomeBean>) {
                onSuccessCallback(homeBeans)
            }

            override fun onError(errorCode: String, error: String) {
                onErrorCallback(errorCode, error)
            }
        })
    }


    fun getActivatorToken(
        homeId: Long,
        onSuccessCallback: (String) -> Unit,
        onErrorCallback: (String) -> Unit,
    ) {
        ThingHomeSdk.getActivatorInstance().getActivatorToken(homeId,
            object : IThingActivatorGetToken {
                override fun onSuccess(token: String) {
                    onSuccessCallback(token)
                }

                override fun onFailure(s: String, s1: String) {
                }
            })

    }


    fun startConfigNetwork(
        context: Context,
        ssid: String,
        password: String,
        token: String,
        onSuccessCallback: (DeviceBean?) -> Unit,
        onErrorCallback: (String?, String?) -> Unit,
    ) {
        val builder = ActivatorBuilder()
            .setSsid(ssid)
            .setContext(context)
            .setPassword(password)
            .setActivatorModel(ActivatorModelEnum.THING_EZ)
            .setTimeOut(120)
            .setToken(token)
            .setListener(object : IThingSmartActivatorListener {
                override fun onError(errorCode: String?, errorMsg: String?) {
                    Log.e(TAG, "onError: $errorCode, $errorMsg")
                    onErrorCallback(errorCode, errorMsg)
                }

                override fun onActiveSuccess(devResp: DeviceBean?) {
                    Log.i(TAG, "onActiveSuccess: ${devResp.toJson()}")
                    onSuccessCallback(devResp)
                }

                override fun onStep(step: String?, data: Any?) {
                    Log.d(TAG, "onStep: $step, $data")
                }
            })

        val mThingActivator = ThingHomeSdk.getActivatorInstance().newMultiActivator(builder)

        //开始配网
        mThingActivator.start()

    }


    fun getActivatorToken(onSuccessCallback: (String, Long) -> Unit, onError: (String?) -> Unit) {
        getHomeId(
            onSuccessCallback = { homeId ->
                ThingHomeSdk.getActivatorInstance().getActivatorToken(homeId,
                    object : IThingActivatorGetToken {
                        override fun onSuccess(token: String) {
                            Log.i(TAG, "getActivatorToken: token: $token")
                            onSuccessCallback(token, homeId)
                        }

                        override fun onFailure(errorCode: String, error: String) {
                            onError("errorCode = $errorCode error = $error")
                        }
                    })
            },
            onErrorCallback = {

            }
        )

    }


    fun stopConfigNetwork(
        context: Context,
        ssid: String,
        password: String,
        token: String,
    ) {
        val builder = ActivatorBuilder()
            .setSsid(ssid)
            .setContext(context)
            .setPassword(password)
            .setActivatorModel(ActivatorModelEnum.THING_EZ)
            .setTimeOut(60)
            .setToken(token)
            .setListener(object : IThingSmartActivatorListener {
                override fun onError(errorCode: String?, errorMsg: String?) {
                    Log.e(TAG, "onError: $errorCode, $errorMsg")
                }

                override fun onActiveSuccess(devResp: DeviceBean?) {
                    Log.i(TAG, "onActiveSuccess: ${devResp.toJson()}")
                }

                override fun onStep(step: String?, data: Any?) {
                    Log.d(TAG, "onStep: $step, $data")
                }


            })

        val mThingActivator = ThingHomeSdk.getActivatorInstance().newMultiActivator(builder)

        //停止配网
        mThingActivator.stop()

        //退出页面销毁一些缓存和监听
        mThingActivator.onDestroy()

    }


    fun getHomeDetail(
        onSuccessCallback: (List<DeviceBean>) -> Unit,
        onErrorCallback: (String) -> Unit,
    ) {

        getHomeId (
            onSuccessCallback = {
                ThingHomeSdk.newHomeInstance(it).getHomeDetail(object : IThingHomeResultCallback {
                    override fun onSuccess(homeBean: HomeBean) {
                        val deviceList: List<DeviceBean> = homeBean.deviceList
                        //下文中的deviceBean就是从这里获取
                        Log.i(TAG, "getHomeDetail onSuccess: ${deviceList.toJson()}")
                        onSuccessCallback(deviceList)
                    }

                    override fun onError(errorCode: String, errorMsg: String) {
                        Log.i(TAG, "onError: $errorCode, errorMsg $errorMsg")
                        onErrorCallback("onError: $errorCode, errorMsg $errorMsg")
                    }
                })
            },
            onErrorCallback = onErrorCallback
        )
    }


    fun getDps(devId: String): MutableMap<String, Any>? {
        return ThingHomeSdk.getDataInstance().getDps(devId)
    }



    fun startLeScan(onResult: (ScanDeviceBean) -> Unit) {

        Log.i(TAG, "startLeScan: ")

        val basicDataStr = AppStore.readString("basicData")

        Log.i(TAG, "basicDataStr: $basicDataStr")

        val baseData = Gson().fromJson(basicDataStr, BasicData::class.java)

        val scanSetting = LeScanSetting.Builder()
            .setTimeout(60000) // 扫描的超时时间：ms
            .addScanType(ScanType.SINGLE)
            .setRepeatFilter(true)
            .build()

        val map = mutableMapOf<String, ScanDeviceBean>()

        // 开始扫描
        ThingHomeSdk.getBleOperator().startLeScan(scanSetting) {

            if (!map.containsKey(it.mac)) {
                Log.i(TAG, "startLeScan: ${it.toJson()}")
                map[it.mac] = it

                // 回调扫描的结果
                if (baseData.deviceIdList?.contains(it.productId) == true) {
                    onResult(it)
                }
            }


        }

    }


    fun getActivatorDeviceInfo(
        scanDeviceBean: ScanDeviceBean,
        onSuccess: (ConfigProductInfoBean) -> Unit
    ) {
        ThingHomeSdk.getActivatorInstance().getActivatorDeviceInfo(
            scanDeviceBean.productId,
            scanDeviceBean.uuid,
            scanDeviceBean.mac,
            object : IThingDataCallback<ConfigProductInfoBean> {
                override fun onSuccess(result: ConfigProductInfoBean) {
                    Log.i(TAG, "HomeScreen: ${result.toJson()}")
                    onSuccess(result)
                }

                override fun onError(errorCode: String, errorMsg: String) {
                    Log.e(TAG, "onError: $errorCode, $errorMsg")
                    UiHandler.showToast(errorMsg)
                }
            })

    }

    fun stopScan() {
        Log.d(TAG, "stopScan: ")
        ThingHomeSdk.getBleOperator().stopLeScan()
    }


    fun startActivator(
        scanDeviceBean: ScanDeviceBean,
        ssid: String,
        passwd: String,
        token: String,
        homeId: Long,
        onSuccessCallback: (DeviceBean) -> Unit,
        onErrorCallback: (String?) -> Unit,
    ) {


        // mScanDeviceBean 来自于扫描回调的 ScanDeviceBean
        val multiModeActivatorBean = MultiModeActivatorBean(scanDeviceBean).apply {
            deviceType = scanDeviceBean.deviceType; // 设备类型
            uuid = scanDeviceBean.uuid; // 设备 uuid
            address = scanDeviceBean.address // 设备地址
            mac = scanDeviceBean.mac; // 设备 mac
            this.ssid = ssid // Wi-Fi SSID
            pwd = passwd // Wi-Fi 密码
            this.token = token // 获取的 Token
            this.homeId = homeId // 当前家庭 homeId
            timeout = 120000; // 超时时间
        }

        Log.i(TAG, "startActivator multiModeActivatorBean: ${multiModeActivatorBean.toJson()}")

        // 开始配网
        ThingHomeSdk.getActivator().newMultiModeActivator()
            .startActivator(multiModeActivatorBean, object :
                IMultiModeActivatorListener {
                override fun onSuccess(deviceBean: DeviceBean) {
                    Log.i(TAG, "onSuccess: ${deviceBean?.toJson()}")
                    onSuccessCallback(deviceBean)
                }

                override fun onFailure(code: Int, msg: String?, handle: Any?) {
                    Log.d(TAG, "onFailure: $code, $msg")
                    onErrorCallback(msg)
                }
            });


    }


    fun stopActivator(uuid:String){
        ThingHomeSdk.getActivator().newMultiModeActivator().stopActivator(uuid)
    }


}